package common

import (
	"bytes"
	"encoding/csv"
	"errors"
	"io"
	"io/ioutil"
	"strings"
)

type CsvParse struct {
	column []string          //列名
	data   map[string]string //数据值
	rows   [][]string        //csv读取到的所有数据
	rowNum int64             //当前数据下标
	len    int               //数据行数
}

// NewCsvParse 解析一个csv文件
func NewCsvParse(filepath string) (*CsvParse, error) {
	fileData, err := ioutil.ReadFile(filepath)
	if err != nil {
		return nil, err
	}
	if len(fileData) > 3 {
		if fileData[0] == 239 && fileData[1] == 187 && fileData[2] == 191 {
			fileData = fileData[3:]
		}
	}
	rows, err := csv.NewReader(bytes.NewReader(fileData)).ReadAll()
	if err != nil {
		return nil, err
	}
	if len(rows) < 1 {
		return nil, errors.New("空数据文件")
	}
	ret := &CsvParse{
		data:   map[string]string{},
		rows:   rows[1:],
		len:    len(rows) - 1,
		rowNum: 0,
	}
	for _, v := range rows[0] {
		ret.column = append(ret.column, strings.TrimSpace(v))
	}
	return ret, nil
}

func (c *CsvParse) Columns() []string {
	return c.column
}

func (c *CsvParse) Len() int {
	return c.len
}

func (c *CsvParse) Restart() {
	c.rowNum = 0
}

func (c *CsvParse) Next() (map[string]string, error) {
	if c.rowNum >= int64(c.len) {
		return nil, io.EOF
	}
	values := c.rows[c.rowNum]
	c.rowNum++
	valuesLen := len(values)
	for i, v := range c.column {
		if i >= valuesLen {
			c.data[v] = ""
			continue
		}
		c.data[v] = values[i]
	}
	return c.data, nil
}

func (c *CsvParse) Index(index int) (map[string]string, error) {
	if index >= c.len || index < 0 {
		return nil, io.EOF
	}
	values := c.rows[index]
	valuesLen := len(values)
	for i, v := range c.column {
		if i >= valuesLen {
			c.data[v] = ""
			continue
		}
		c.data[v] = values[i]
	}
	return c.data, nil
}

func (c *CsvParse) NextValues() ([]string, error) {
	if c.rowNum >= int64(c.len) {
		return nil, io.EOF
	}
	values := c.rows[c.rowNum]
	c.rowNum++
	return values, nil
}
